package com.webchat.rmi.builder;


import com.webchat.common.constants.RpcRequestConstants;
import feign.Feign;
import feign.Request;
import feign.Target;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract;

/**
 * 动态构建RPC客户端
 */
public class FeignClientBuilder<T> {

    private Encoder encoder = new JacksonEncoder();
    private Decoder decoder = new JacksonDecoder();

    private Class<T> targetClass;

    public FeignClientBuilder(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    public T build(String instanceHost) {

        Feign.Builder builder = Feign.builder()
                .encoder(encoder)
                .decoder(decoder)
                .requestInterceptor(template -> {
                        template.header("Content-Type", "application/json");
                        template.header(RpcRequestConstants.RPC_REQUEST_ACCESS_KEY, RpcRequestConstants.RPC_REQUEST_DEFAULT_AK);
                        template.header(RpcRequestConstants.RPC_REQUEST_SECRET_KEY, RpcRequestConstants.RPC_REQUEST_DEFAULT_SK);
                }).contract(new SpringMvcContract());

        // 显式指定 name 和 URL
        Target<T> target = new Target.HardCodedTarget<>(
                targetClass,
                instanceHost,  // 自定义唯一标识
                instanceHost
        );
        return builder.target(target);
    }

}
